package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    //使用JedisPool操作redis
    @Autowired
    private JedisPool jedisPool;

    //注入checkItemDao对象
    @Autowired
    private SetMealDao setMealDao;

    /**
     * 添加套餐功能
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        //添加Setmeal对象,操作t_setmeal表
        setMealDao.add(setmeal);
        //关联检查组对象,操作关联表
        Integer setmealId = setmeal.getId();
        //调用方法
        this.setSetmealAndCheckgroup(setmealId, checkgroupIds);
        //将存入数据库的图片名存入到redis中
        String fileName = setmeal.getImg();
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        //归还池连接
        jedis.close();
    }

    //提取方法,关联套餐与检查组的关系
    public void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds) {

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setMealDao.setCheckGroupAndCheckItem(map);
            }
        }

    }
}
